package com.example.ivideo_2211a.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ItemCategoryBinding
import com.example.ivideo_2211a.model.CategoryModel

/**
 * 分类标签适配器
 */
class CategoryAdapter(
    private val onCategoryClick: (CategoryModel) -> Unit
) : ListAdapter<CategoryModel, CategoryAdapter.CategoryViewHolder>(CategoryDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
        val binding = ItemCategoryBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return CategoryViewHolder(binding)
    }

    override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class CategoryViewHolder(
        private val binding: ItemCategoryBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(category: CategoryModel) {
            binding.categoryText.text = category.name
            
            // 根据选中状态设置颜色
            if (category.isSelected) {
                binding.categoryText.setTextColor(
                    ContextCompat.getColor(binding.root.context, R.color.primary_color)
                )
                binding.categoryIcon.setColorFilter(
                    ContextCompat.getColor(binding.root.context, org.jash.user.R.color.color_agreement)
                )
            } else {
                binding.categoryText.setTextColor(
                    ContextCompat.getColor(binding.root.context, android.R.color.darker_gray)
                )
                binding.categoryIcon.setColorFilter(
                    ContextCompat.getColor(binding.root.context, android.R.color.darker_gray)
                )
            }
            
            binding.root.setOnClickListener {
                onCategoryClick(category)
            }
        }
    }

    class CategoryDiffCallback : DiffUtil.ItemCallback<CategoryModel>() {
        override fun areItemsTheSame(oldItem: CategoryModel, newItem: CategoryModel): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: CategoryModel, newItem: CategoryModel): Boolean {
            return oldItem == newItem
        }
    }
}